package daily;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.lang.math.RandomUtils;

public class ReadWriteLockTest {

	public static void main(String[] args) {
		final Queue queue = new Queue();
		
		for(int i=0;i<3;i++){
			new Thread(new Runnable(){

				@Override
				public void run() {
					while(true){
						queue.get();
					}
					
				}}).start();
			
			
			new Thread(new Runnable(){

				@Override
				public void run() {
					while(true){
						queue.write(RandomUtils.nextInt(1000));
					}
				}}).start();
			
		}

	}
	
	
}

	class Queue{
		private Object data=null;
		ReadWriteLock rwl=new ReentrantReadWriteLock();
		
		public void get(){
			rwl.readLock().lock();
			try{
				System.out.println(Thread.currentThread().getName()+" begin to read data! ");
				Thread.sleep(RandomUtils.nextInt(1000));
				System.out.println(Thread.currentThread().getName()+" have  read data! "+ data);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				rwl.readLock().unlock();
			}
		}
		
		public void write(Object data){
			rwl.writeLock().lock();
			try{
				System.out.println(Thread.currentThread().getName()+" begin to write data! ");
				Thread.sleep(RandomUtils.nextInt(1000));
				this.data=data;
				System.out.println(Thread.currentThread().getName()+" have  write data! "+ data);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				rwl.writeLock().unlock();
			}
		}
					
	}